package cn.linlane.dao.sys;

import cn.linlane.dao.BaseDao;
import cn.linlane.entity.sys.SysDepart;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

public interface SysDepartDao extends BaseDao<SysDepart, Integer> {
    /**
     * 查询子节点
     * @param parentId
     * @return
     */
    List<SysDepart> findAllByParentId(Long parentId);
    /**
     * 查询根据Id查询组织机构
     * @param Id
     * @return
     */
    SysDepart findByParentId(Long Id);

    /**
     * 根据id storeName模糊查询
     * @return
     */
    @Query("select sysDepart from SysDepart sysDepart " +
            "where (?1 is null or sysDepart.parentId = ?1) " +
            "and ( sysDepart.storeCode like %?2% or sysDepart.storeName like %?2% ) ")
    Page<SysDepart> fetchAllByParentId(Long id, String storeName, Pageable pageable);

    /**
     * 根据编号查询状态
     * @param storeCode
     * @return
     */
    List<SysDepart> findByStoreCode(String storeCode);

    /**
     * 根据门店编号查询所有部门
     * @param storeCode
     * @return
     */
    List<SysDepart> findAllByStoreCodeIn(Set<String> storeCode);


    Boolean existsAllByStoreCode(String storeCode);

    /**
     * 查看门店是否可以下发卡
     * @return
     */
    @Query("select s from SysDepart s where s.storeCode = ?1")
    SysDepart findDistributeStores(String storeCode);

    @Modifying
    @Transactional(rollbackFor = RuntimeException.class)
    @Query(value = "delete from sys_user_data_permition where data_permition = ?1", nativeQuery = true)
    void deleteDataPermition(Long id);

    @Modifying
    @Transactional(rollbackFor = RuntimeException.class)
    @Query(value = "insert into sys_user_data_permition values (?1, ?2)", nativeQuery = true)
    void insertDataPermition(Long id, String storeCode);

    @Query(value = "select data_permition from sys_user_data_permition where sys_user_id = ?1", nativeQuery = true)
    Set<String> findAllDatePermition(Long userId);
}
